<template>
  <div class="page-main" v-title data-title="工程采购申请单">
    <home-nav :userData="userinfo"></home-nav>
    <div class="banner"><span>工程采购申请单</span></div>
    <div class="container">
      <div class="head-content">
        <span class="bold-font">工程采购申请单</span>
        <div class="btn-line">
          <a-button icon="a-icon-files" type="primary" @click="handlerSave">保存</a-button>
          <a-button icon="a-icon-s-grid" plain @click="handlerSubmit">提交到HIP</a-button>
        </div>
      </div>
      <div class="app-container">
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          style="margin-top: 10px"
          label-width="160px"
          label-position="right"
        >
          <section>
            <div class="section-header">项目信息</div>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="采购申请号:">
                  <a-input v-model="form.applyNo" placeholder="自动生成流水号" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申领人/部门:">
                  <a-input
                    :value="form.createUser && form.createDept ? form.createUser + '/' + form.createDept : ''"
                    disabled
                    placeholder="自动带入信息"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间:">
                  <a-date-picker
                    disabled
                    style="width: 100%"
                    valueFormat="YYYY-MM-DD"
                    v-model="form.createTime"
                    placeholder="自动带入时间"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="项目编号:">
                  <a-input-search
                    readOnly
                    placeholder="项目编号"
                    v-model="form.projectCode"
                    @search="openProjectSelector"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目名称:">
                  <a-input v-model="form.projectName" placeholder="项目名称" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="项目经理:">
                  <a-input v-model="form.projectManager" placeholder="项目经理" disabled />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="采购项名称:" prop="itemName">
                  <a-input v-model="form.itemName" placeholder="采购项名称" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="费用支出号:" prop="costNumber">
                  <a-input-search
                    readOnly
                    placeholder="费用支出号"
                    v-model="form.costNumber"
                    @search="openProjectCostSelector"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="签订公司:" prop="signCompany">
                  <a-select v-model="form.signCompanyCode">
                    <a-select-option
                      v-for="(item, index) in signCompany"
                      :key="'companyName' + index"
                      :value="item.componyNo"
                    >
                      {{ item.componyName + '/' + item.componyNo }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="使用车间:" prop="useDept">
                  <a-input v-model="form.useDept" placeholder="使用车间" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="用途:" prop="useMark">
                  <a-input v-model="form.useMark" placeholder="用途" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="现场跟进人:" prop="followPerson">
                  <UserInputSelector
                    :username.sync="form.followPersonId"
                    :realname.sync="form.followPerson"
                    multiple="multiple"
                    placeholder="请选择"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="预算金额(元):" prop="budget">
                  <a-input v-model="form.budgetAmount" placeholder="求和预算项不含税总价" />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="合同生效日期:" prop="contractTime">
                  <a-date-picker
                    style="width: 100%"
                    valueFormat="YYYY-MM-DD"
                    v-model="form.contractTime"
                    placeholder="要求合同生效时间"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="要求最晚到货/进场时间:" prop="arriveTime">
                  <a-date-picker
                    style="width: 100%"
                    valueFormat="YYYY-MM-DD"
                    v-model="form.arriveTime"
                    placeholder="自动带入时间"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="24">
                <a-form-model-item label="采购申请说明:" prop="applyRemark">
                  <a-textarea
                    :auto-size="{ minRows: 3, maxRows: 10 }"
                    :maxLength="500"
                    v-model="form.applyRemark"
                    placeholder="由申请人补充采购申请说明"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="是否数字贷：">
                  <a-radio-group name="radioGroup" v-model="form.digitalLoan" @change="changeDigitalLoan">
                    <a-radio v-for="(code, index) in yesOrNot" :key="index" :value="code.code">
                      {{ code.name }}
                    </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item label="备案证名称：">
                  <a-select v-model="form.filingName" :disabled="!form.digitalLoan">
                    <a-select-option
                      v-for="(item, index) in codes['数字贷备案证名称']"
                      :key="'filingName' + index"
                      :value="item.name"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
          </section>
          <section>
            <div class="section-header">采购想明细</div>
            <div style="display: flex; justify-content: flex-end">
              <a-button icon="a-icon-download" type="primary" @click="openEngineeBudgetSelector()">选择采购项</a-button>
              <a-button icon="a-icon-s-grid" plain @click="removeItem">删除</a-button>
            </div>
            <a-table
              class="hte-table-content"
              :columns="columns"
              :data-source="itemList"
              :pagination="false"
              size="middle"
              rowKey="budgetId"
              :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            >
              <template slot="indexRander" slot-scope="text, record, index">
                {{ index + 1 }}
              </template>
              <template slot="applyNumRander" slot-scope="text, record, index">
                <a-input v-model="record.applyNum" type="number" @change="changeApplyNum(index)" />
              </template>
              <template slot="remarkRander" slot-scope="text, record">
                <a-textarea
                  v-model="record.remark"
                  placeholder="问题描述"
                  :auto-size="{ minRows: 1, maxRows: 20 }"
                  :maxLength="500"
                />
              </template>
            </a-table>
          </section>
        </a-form-model>
      </div>
    </div>
    <projectSelector @close="closeProjectSelector" ref="projectSelector" />
    <projectCostSelector @close="closeProjectCostSelector" ref="projectCostSelector" />
    <engineeBudgetSelector @selected="selectEngineeBudgetSelector" ref="engineeBudgetSelector" />
  </div>
</template>
<script>
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { postAction, getAction } from '@/api/manage'
export default {
  name: 'PurchaseApply',
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    projectSelector: () => import('@/views/projectBuild/projectSelector'),
    projectCostSelector: () => import('@/views/projectBuild/projectCostSelector'),
    engineeBudgetSelector: () => import('@/views/purchase/engineeBudgetSelector'),
  },
  data() {
    return {
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'HtePurchaseApplyEdit',
      },
      urls: {
        loadSignCompany: '/hte/contract/loadSignCompany',
        info: 'htePurchaseApply/info',
        itemList: 'htePurchaseApply/item/list',
        edit: 'htePurchaseApply/edit',
        saveItem: 'htePurchaseApply/saveItem',
        deleteItem: '/htePurchaseApply/item/delete',
        codes: '/manage/codeInfo/queryByTypes',
      },
      rules: {
        itemName: [
          { required: true, message: '请输入采购项名称', trigger: 'change' },
          { required: true, message: '请输入采购项名称', trigger: 'change' },
        ],
        costNumber: [{ required: true, message: '请输入费用支出号', trigger: 'change' }],
        signCompany: [{ required: true, message: '请选择签订公司', trigger: 'change' }],
        useDept: [{ required: true, message: '请输入使用车间', trigger: 'change' }],
        useMark: [{ required: true, message: '请输入用途', trigger: 'change' }],
        followPerson: [{ required: true, message: '请输入现场跟进人', trigger: 'change' }],
        budgetAmount: [{ required: true, message: '请输入预算金额s', trigger: 'change' }],
        contractTime: [{ required: true, message: '请选择合同生效时间', trigger: 'change' }],
        arriveTime: [{ required: true, message: '请选择进场到货时间', trigger: 'change' }],
        applyRemark: [{ required: true, message: '请输入采购申请说明', trigger: 'change' }],
      },
      form: {},
      itemList: [],
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'indexRander' },
          width: '60px',
        },
        {
          title: '预算分类',
          dataIndex: 'budgetType',
          key: 'budgetType',
          width: '120px',
          scopedSlots: { customRender: 'budgetTypeRander' },
        },
        {
          title: '预算项名称',
          dataIndex: 'budgetItem',
          key: 'budgetItem',
          width: '300px',
        },
        {
          title: '单位',
          dataIndex: 'unit',
          key: 'unit',
          width: '300px',
        },
        {
          title: '数量',
          dataIndex: 'applyNum',
          key: 'applyNum',
          width: '200px',
          scopedSlots: { customRender: 'applyNumRander' },
        },
        {
          title: '税率',
          dataIndex: 'taxRate',
          key: 'taxRate',
          width: '200px',
        },
        {
          title: '含税单价(万元)',
          dataIndex: 'includeTaxPriceUnit',
          key: 'includeTaxPriceUnit',
          width: '200px',
        },
        {
          title: '不含税单价(万元)',
          dataIndex: 'noTaxPriceUnit',
          key: 'noTaxPriceUnit',
          width: '200px',
        },
        {
          title: '含税总价(万元)',
          dataIndex: 'includeTaxPriceAll',
          key: 'includeTaxPriceAll',
          width: '200px',
        },
        {
          title: '不含税总价(万元)',
          dataIndex: 'noTaxPriceAll',
          key: 'noTaxPriceAll',
          width: '200px',
        },
        {
          title: '备注说明',
          dataIndex: 'remark',
          key: 'remark',
          width: '200px',
          scopedSlots: { customRender: 'remarkRander' },
        },
      ],
      signCompany: [],
      selectedRows: [],
      selectedRowKeys: [],
      yesOrNot: [
        { code: false, name: '否' },
        { code: true, name: '是' },
      ],
      codes: {},
    }
  },

  created() {
    this.fetchSignCompany()
    this.fetchCodes()
  },
  computed: {
    userDept() {
      return this.form.applyUserName + '/' + this.form.applyDeptName
    },
  },
  methods: {
    fetchCodes() {
      let types = []
      types.push('数字贷备案证名称')
      getAction(this.urls.codes, { types: types.join(',') }).then((res) => {
        if (res.success) {
          this.codes = { ...this.codes, ...res.result }
        }
      })
    },
    updateInit(id) {
      if (id) {
        this.fetchApply(id)
        this.fetchApplyItem(id)
      }
    },
    fetchApply(id) {
      if (id) {
        getAction(this.urls.info, { id: id }).then((res) => {
          if (res.code == 200) {
            this.form = res.result
          } else {
            this.$message.warning('请求数据失败:' + res.message)
          }
        })
      }
    },
    fetchApplyItem(id) {
      if (id) {
        postAction(this.urls.itemList, { applyId: id }).then((res) => {
          if (res.code == 200) {
            this.itemList = res.result
          } else {
            this.$message.warning('请求数据失败:' + res.message)
          }
        })
      }
    },
    fetchSignCompany() {
      getAction(this.urls.loadSignCompany, {}).then((res) => {
        if (res.code == 200) {
          this.signCompany = res.result
        } else {
          this.$message.warning('请求数据失败:' + res.msg)
        }
      })
    },
    async handlerSave() {
      if (this.form.signCompanyCode) {
        for (let company of this.signCompany) {
          if (company.componyNo == this.form.signCompanyCode) {
            this.$set(this.form, 'signCompany', company.componyName)
          }
        }
      }
      this.$set(this.form, 'itemList', this.itemList)
      let res = await postAction(this.urls.edit, this.form)
      if (res.success) {
        this.form = res.result
        this.fetchApply(this.form.id)
        this.fetchApplyItem(this.form.id)
        this.$message.success('保存成功')
        return true
      } else {
        this.$message.warning('保存失败:' + res.message)
        return false
      }
    },
    handlerSubmit() {
      if (this.checkItemList()) {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            if (this.handlerSave()) {
              this.openHip()
            }
          } else {
            this.$message.warning('请根据提示将表单填写完整')
          }
        })
      }
    },
    openHip() {
      const token = Vue.ls.get(ACCESS_TOKEN)
      window.open(
        process.env.VUE_APP_HIP_API_BASE_URL +
          '/common/mainTree.do?rturl=%2FHIP%2Fprojectapply%2FprojectInfoList.do%3FhteOpen%3Dtrue%26hteId%3D' +
          this.form.id +
          '&hteToken=' +
          token
      )
    },
    openProjectSelector() {
      this.$refs.projectSelector.openInit({ projectClasses: ['40', '41'], withOutProjectSubTypes: ['S'] })
    },
    closeProjectSelector(project) {
      if (project) {
        this.$set(this.form, 'projectBuildId', project.id)
        this.$set(this.form, 'projectCode', project.projectNo)
        this.$set(this.form, 'projectName', project.projectName)
        this.$set(this.form, 'projectManager', project.projectManager)
        this.$set(this.form, 'projectManagerId', project.projectManagerId)
        this.$set(this.form, 'digitalLoan', project.digitalLoan)
        this.$set(this.form, 'filingName', project.filingName)
      }
    },
    openProjectCostSelector() {
      if (this.form.projectCode) {
        this.$refs.projectCostSelector.openInit({ projectNo: this.form.projectCode })
      } else {
        return this.$message.warning('请先选择项目')
      }
    },
    closeProjectCostSelector(cost) {
      if (cost) {
        this.$set(this.form, 'costNumber', cost.wbsCode)
      }
    },
    openEngineeBudgetSelector() {
      if (this.form.projectBuildId) {
        this.$refs.engineeBudgetSelector.openInit(this.form.projectBuildId, this.form.id)
      } else {
        return this.$message.warning('请先选择项目')
      }
    },
    selectEngineeBudgetSelector(selectedRows) {
      if (selectedRows && selectedRows.length > 0) {
        for (let selected of selectedRows) {
          let exists = false
          for (let item of this.itemList) {
            if (item.budgetId == selected.id) {
              exists = true
            }
          }
          if (exists) {
            return this.$message.warning(
              '[' + selected.budgetType + '][' + selected.budgetItem + ']已存在,请勿重复选择'
            )
          } else {
            let item = selected
            item.budgetId = selected.id
            delete item.id
            delete item.createTime
            delete item.createUser
            delete item.createUserId
            delete item.updateTime
            delete item.updateUser
            delete item.updateUserId
            item.noTaxPriceAll = item.applyNum * item.noTaxPriceUnit
            item.includeTaxPriceAll = item.applyNum * item.includeTaxPriceUnit
            this.itemList.push(item)
          }
        }
      }
      this.calcApplyBudget()
    },
    changeApplyNum(index) {
      this.checkItemList(index)
    },
    checkItemList(index) {
      if (index) {
        let item = this.itemList[index]
        if (!item.applyNum) {
          this.$message.warning('请输入行[' + index + ']数量')
          return false
        }
        if (item.applyNum > item.lessNum) {
          this.$message.warning('行[' + index + ']数量[' + item.applyNum + ']不能大于[' + item.lessNum + ']')
          this.$set(this.itemList[index], 'applyNum', item.lessNum)
          return false
        }
        this.$set(this.itemList[index], 'noTaxPriceAll', item.applyNum * item.noTaxPriceUnit)
        this.$set(this.itemList[index], 'includeTaxPriceAll', item.applyNum * item.includeTaxPriceUnit)
      } else {
        let index = 0
        for (let item of this.itemList) {
          if (!item.applyNum) {
            this.$message.warning('请输入行[' + index + ']数量')
            return false
          }
          if (item.applyNum > item.lessNum) {
            this.$message.warning('行[' + index + ']数量[' + item.applyNum + ']不能大于[' + item.lessNum + ']')
            this.$set(this.itemList[index], 'applyNum', item.lessNum)
            return false
          }
          this.$set(this.itemList[index], 'noTaxPriceAll', item.applyNum * item.noTaxPriceUnit)
          this.$set(this.itemList[index], 'includeTaxPriceAll', item.applyNum * item.includeTaxPriceUnit)
          index++
        }
      }
      this.calcApplyBudget()
      return true
    },
    onSelectChange(selectedRowKeys, selectedRow) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRow
    },
    async removeItem() {
      if (!this.selectedRows || this.selectedRows.length <= 0) {
        return this.$message.warning('请至少选择一条记录惊醒操作')
      }
      let ids = []
      let newItemList = []
      for (let row of this.selectedRows) {
        if (row.id) {
          ids.push(row.id)
        }
      }
      for (let item of this.itemList) {
        if (this.selectedRows.indexOf(item) < 0) {
          newItemList.push(item)
        }
      }
      if (ids && ids.length > 0) {
        let res = await getAction(this.urls.deleteItem, { ids: ids.join(',') })
        if (!res.success) {
          return this.$message.error('删除失败:' + res.message)
        }
      }
      this.$message.success('删除成功')
      this.itemList = newItemList
      this.selectedRows = []
      this.selectedRowKeys = []
      this.calcApplyBudget()
    },
    calcApplyBudget() {
      let budget = 0
      for (let item of this.itemList) {
        budget += parseFloat(item.noTaxPriceAll)
      }
      this.$set(this.form, 'budgetAmount', budget)
    },
    changeDigitalLoan() {
      if (!this.form.digitalLoan) {
        this.$set(this.form, 'filingName', '')
      }
    },
  },
}
</script>

<style scoped>
.demo-table-expand .a-form-model-item {
  margin-right: 0;
  margin-bottom: 0px;
}

.demo-table-expand span {
  display: inline-block;
  white-space: nowrap;
  width: 95%;
  overflow: hidden;
  text-overflow: ellipsis;
}

.a-form-model-item >>> .a-form-model-item--mini .a-form-model-item__label {
  color: #606266 !important;
  font-size: 12px !important;
  font-weight: normal;
}

.a-table >>> .a-table__expanded-cell[class*='cell'] {
  padding: 0px 0px 10px 0px;
}

.expand-title {
  height: 30px;
  line-height: 30px;
  background-color: #f1f1f1;
  padding-left: 50px;
  margin-bottom: 5px;
  font-size: 12px;
}

.a-form-model-item >>> .a-form-model-item__content {
  height: 36px;
}

.ellipse-tooltips {
  display: inline-block;
  white-space: nowrap;
  width: 95%;
  overflow: hidden;
  text-overflow: ellipsis;
}

.ellipse-tooltips span {
  width: unset !important;
}

.a-range >>> .a-range-separator {
  width: 20px;
}

.searchForm {
  display: flex;
  flex-direction: row;
}

.searchForm-left {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: flex-start;
  width: 85vw;
}

.searchForm-right {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
  min-width: 280px;
  border-left: #cccccc 2px solid;
}
</style>

<style lang="less" scoped>
@import '~@assets/less/hte-main.less';

.page-main {
  .banner {
    background-image: url(~@assets/contract-top.png);
  }

  .container {
    .content-list {
      margin-top: 15px;
    }
  }

  .font-active {
    cursor: pointer;
  }
}

/deep/.ant-select-dropdown {
  width: 400px !important;
}
</style>

